<%@LANGUAGE="JAVASCRIPT" %>
<!--#include file ="../Includes/JSON2.asp"-->
<!--#include file ="../Includes/DB.asp"--> 
<!--#include file ="../Includes/ASPHelpers.asp"-->
<!--#include file ="../Includes/User.asp"-->

<%


var API = {
		NoMethod: function(){
			var ret = {};
			ret.Success = false;
			ret.ErrorMessage = "No Method Passed";
			
			return JSON.stringify(ret);
		},
		
		/*----------------------------------------------------------------------*/
		MethodNotFound: function(){
			var ret = {};
			ret.Success = false;
			ret.ErrorMessage = "AJAX method '" + originalMethod + "' does not exist.";
			
			return JSON.stringify(ret);
		},
		
		/*----------------------------------------------------------------------*/
		SaveScript: function(){
			var ret = {};
			ret.Success = "";
			ret.Data = "";
			ret.ErrorMessage = "";


			var scriptID = 	new String(Request.Form("scriptID"));
			var category = 	Server.HTMLEncode(Request.Form("category"));
			var title = 	Server.HTMLEncode(Request.Form("title"));
			var user = 		User.CurrentUser() || "(unknown)";
			var queryName = "";

			var addBaseScriptBlock = false;


			if(scriptID == "new"){
				scriptID = 		Helpers.CreateTimeStampDBID();
				queryName = 	"qrySaveNewScript";
				addBaseScriptBlock = true;
			}
			else{
				queryName = 	"qrySaveExistingScript";
			}
			
			
			
			var db, rs;
			db = new DB.DataCall();
			//db.SQL = sql;
			db.QueryName = queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
			db.AddParameter("@Category", DB.DataTypes.String, category);
			db.AddParameter("@Title", DB.DataTypes.String, title);
			db.AddParameter("@UserID", DB.DataTypes.String, user);
			
			db.Execute();
			

			/* if successfully saved script and was a new script then also create primary scriptBlock */
			if(db.Success && addBaseScriptBlock){
				db = new DB.DataCall();
				db.QueryName = 			"qrySaveNewScriptBlock";
				db.ConnectionString = 	DB.ConnectionStrings.Scripts;
				db.CommandType = 		DB.CommandTypes.StoredProc;
				newScriptBlockID =		Helpers.CreateTimeStampDBID();
			
				db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
				db.AddParameter("@ScriptBlockID", DB.DataTypes.String, newScriptBlockID);
				db.AddParameter("@DecisionID", DB.DataTypes.String, "0");
				db.AddParameter("@DecisionTitle", DB.DataTypes.String, "");
				db.AddParameter("@ScriptText", DB.DataTypes.String, "New script", 65000);
				db.AddParameter("@UserID", DB.DataTypes.String, user);
			
				db.Execute();

				ret.NewScriptBlockID = newScriptBlockID;
				ret.debug = db;

			}

			ret.Success = 		db.Success;
			ret.ErrorMessage = 	db.ErrorMessage;
			ret.Data = 			scriptID;
			
			return JSON.stringify(ret);
		},
		
		/*----------------------------------------------------------------------*/
		SaveScriptBlock: function(){
			var ret = {};
			ret.Success = "";
			ret.Data = "";
			ret.ErrorMessage = "";
			
			var scriptID = 		    new String(Request.Form("scriptID"));
			var scriptBlockID =     new String(Request.Form("ScriptBlockID"));
			var decisionID = 	    new String(Request.Form("DecisionID"));
			var decisiontTitle =    Server.HTMLEncode(Request.Form("DecisionTitle"));
			var scriptText = 	    Server.HTMLEncode(Request.Form("ScriptText"));
			var user = 			    User.CurrentUser() || "(unknown)";
			var queryName = 	    "";
			


			if(scriptBlockID == "new"){
				scriptBlockID = Helpers.CreateTimeStampDBID();
				queryName = 	"qrySaveNewScriptBlock";
			}
			else{
				queryName = 	"qrySaveExistingScriptBlock";
			}
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
			db.AddParameter("@ScriptBlockID", DB.DataTypes.String, scriptBlockID);
			db.AddParameter("@DecisionID", DB.DataTypes.String, decisionID);
			db.AddParameter("@DecisionTitle", DB.DataTypes.String, decisiontTitle);
			db.AddParameter("@ScriptText", DB.DataTypes.String, scriptText, 65000);
			db.AddParameter("@UserID", DB.DataTypes.String, user);
			
			db.Execute();
			
			ret.Success = 		db.Success;
			ret.ErrorMessage = 	db.ErrorMessage;
			ret.Data = 			scriptBlockID;
			ret.Debug = 		db;

			
			return JSON.stringify(ret);
		},
		
		/*----------------------------------------------------------------------*/
		SaveNewDecision: function(){
			var ret = {};
			ret.Success = "";
			ret.Data = {};
			ret.ErrorMessage = "";
			
			var parentScriptBlockID = 	new String(Request.Form("ScriptBlockID"));
			var scriptID = 				new String(Request.Form("scriptID"));
			var order =					new String(Request.Form("order"));
			var decisionTitle = 		"New Decision";
			var user = 					User.CurrentUser() || "(unknown)";
			var newDecisionID, queryName
			
			
			if(Helpers.IsNullOrEmpty(parentScriptBlockID)){
				ret.Success = 		false;
				ret.ErrorMessage = 	"No ScriptBlockID sent.";
				
				return JSON.stringify(ret);
			}
			
			newDecisionID = Helpers.CreateTimeStampDBID();
			queryName = 	"qrySaveNewDecision";
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
			db.AddParameter("@ScriptBlockID", DB.DataTypes.String, parentScriptBlockID);
			db.AddParameter("@DecisionID", DB.DataTypes.String, newDecisionID);
			db.AddParameter("@DecisionTitle", DB.DataTypes.String, decisionTitle);
			db.AddParameter("@Order", DB.DataTypes.String, order);
			db.AddParameter("@UserID", DB.DataTypes.String, user);
			
			db.Execute();
			
			if(!db.Success){
				db.ErrorMessage += " (qrySaveNewDecision)";
			}
			
			//if success then make call to saveNewScriptBlock with new decisionID command too.
			if(db.Success){
				var newScriptBlockID = 	Helpers.CreateTimeStampDBID();
				var scriptText = 		"New script.";
				queryName = 			"qrySaveNewScriptBlock";
				
				
				db = new DB.DataCall();
				db.QueryName = 			queryName;
				db.ConnectionString = 	DB.ConnectionStrings.Scripts;
				db.CommandType = 		DB.CommandTypes.StoredProc;
				
				db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
				db.AddParameter("@ScriptBlockID", DB.DataTypes.String, newScriptBlockID);
				db.AddParameter("@DecisionID", DB.DataTypes.String, newDecisionID);
				db.AddParameter("@DecisionTitle", DB.DataTypes.String, "");
				db.AddParameter("@ScriptText", DB.DataTypes.String, scriptText);
				db.AddParameter("@UserID", DB.DataTypes.String, user);
				
				db.Execute();
				
				if(!db.Success){
					db.ErrorMessage += " (qrySaveNewScriptBlock)";
				}
				
			}
			
			
			ret.Success = 				db.Success;
			ret.ErrorMessage = 			db.ErrorMessage;
			ret.Data.NewDecisionID = 	newDecisionID;
			ret.Data.NewDecisionTitle = decisionTitle;
			ret.Data.NewScriptBlockID = newScriptBlockID;
			ret.Data.NewScriptText = 	scriptText;

			
			return JSON.stringify(ret);
		},
		
		/*----------------------------------------------------------------------*/
		LoadExistingDecision: function(){
			var ret = {};
			ret.Success = "";
			ret.Data = {};
			ret.ErrorMessage = "";
			
			var scriptBlockID = 	new String(Request.Form("ScriptBlockID"));
			
			if(Helpers.IsNullOrEmpty(scriptBlockID)){
				ret.Success = 		false;
				ret.ErrorMessage = 	"No ScriptBlockID sent.";
				
				return JSON.stringify(ret);
			}
		
			queryName = 	"qryGetScriptBlockByScriptBlockID";
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptBlockID", DB.DataTypes.String, scriptBlockID);
			
			db.Execute();
			
			ret.Success = db.Success;
			
			if(db.Success){
				rs = db.RecordSet;
				
				if(rs.RecordCount > 0){
					rs.MoveFirst();
					
					ret.Data.ScriptBlockID = 	rs.fields("ScriptBlockID").value;
					ret.Data.DecisionID =		rs.fields("DecisionID").value;
					ret.Data.ScriptText = 		Helpers.DecodeHTML(rs.fields("ScriptText").value);
					ret.Data.Decisions =		[];
					
					/* get decisions for this scriptblock */
					queryName = 			"qryGetDecisionsAndChildScriptBlock";
					
					db = new DB.DataCall();
					db.QueryName = 			queryName;
					db.ConnectionString = 	DB.ConnectionStrings.Scripts;
					db.CommandType = 		DB.CommandTypes.StoredProc;
			
					db.AddParameter("@ScriptBlockID", DB.DataTypes.String, ret.Data.ScriptBlockID);
					
					db.Execute();
					
					ret.Success = db.Success;
					ret.Debug = db;
					
					if(db.Success){
						rs = db.RecordSet;
						
						while(!rs.EOF){
							var decision = {
								DecisionID:			rs.fields("DecisionID").value,
								ScriptBlockID:		rs.fields("ScriptBlockID").value,
								ChildScriptBlockID:	rs.fields("ChildScriptBlockID").value || "",
								DecisionTitle:		Helpers.DecodeHTML(rs.fields("DecisionTitle").value)
							}

						ret.Data.Decisions.push(decision);
						
						rs.MoveNext();
						}
					}
					else{
						ret.ErrorMessage = db.ErrorMessage + " (qryGetDecisionsAndChildScriptBlock)";
					}
					
				}
				else{
					ret.Data.ScriptBlockID =	"new";
					ret.Data.DecisionID =		"";
					ret.Data.ScriptText =		"New script.";
					ret.Data.Decisions =		[];
				}
			}
			else{
				ret.ErrorMessage = db.ErrorMessage + " (qryGetScriptBlockByScriptBlockID)";
				ret.Data = db;
			}
			
			return JSON.stringify(ret);
			
		},
		
		/*----------------------------------------------------------------------*/
		SaveDecisionOrder: function(){
			var ret = {};
			ret.Success = "";
			ret.Data = {};
			ret.ErrorMessage = "";
			
			var scriptBlockID = 	new String(Request.Form("ScriptBlockID"));
			var order =				new String(Request.Form("Order"));
			var orderArr =			order.split(",");
			var sql =				"";
			
			if(Helpers.IsNullOrEmpty(scriptBlockID)){
				ret.Success = 		false;
				ret.ErrorMessage = 	"No ScriptBlockID sent.";
				
				return JSON.stringify(ret);
			}
			
			queryName = 	"qrySaveDecisionOrder";
			
			var db, rs;
			db = new DB.DataCall();
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			
			/* there is no way of running an Access function through ADO and I cant get an update to work with a join on a derived table so the only way to get this to work is
			 * to build this retarded sql statement using iif */
			sql = "UPDATE tblDecisions SET tblDecisions.[order] = (";
			
			for (var x = 0, len = orderArr.length; x < len; x++){
				if(x < len){
					sql += "iif(DecisionID ='" + orderArr[x] + "'," + x + ",";
				}
				else{
					sql += "0"; //the last else in the chain of iif's gets a '0'
				}
			}
			
			sql += Array(orderArr.length + 2).join(")");

			sql += " WHERE ScriptBlockID = '" + scriptBlockID + "'";

			db.SQL = sql;
			
			db.Execute();
			ret.Debug = db;
			
			ret.Success = db.Success;
			ret.ErrorMessage = db.ErrorMessage;
			
			if(db.Success){
				//ret.Data.SuccessCount = rs.fields("response").value;
			}
			
			return JSON.stringify(ret);
		},
		
		/*----------------------------------------------------------------------*/
		DeleteDecision : function(){
			var ret = {};
			ret.Success = "";
			ret.Data = {};
			ret.ErrorMessage = "";
			
			var decisionID = 	new String(Request.Form("DecisionID"));
			
			if(Helpers.IsNullOrEmpty(decisionID)){
				ret.Success = 		false;
				ret.ErrorMessage = 	"No DecisionID sent.";
				
				return JSON.stringify(ret);
			}
			
			queryName = 	"qryDeleteDecision";
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
	
			db.AddParameter("@DecisionID", DB.DataTypes.String, decisionID);
			
			db.Execute();
			
			ret.Success = db.Success;
			ret.ErrorMessage = db.ErrorMessage;
			
			
			return JSON.stringify(ret);
		
		
		},
		
		/*----------------------------------------------------------------------*/
		GetScripts: function(){
			var ret =           {};
			ret.Success =       "";
			ret.Data =          {};
			ret.ErrorMessage =  "";
			
			
			queryName =          	"qryGetScripts";
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			

			db.Execute();
		
			ret.Success = db.Success;
			ret.ErrorMessage = db.ErrorMessage;

			if(db.Success){
				rs = db.RecordSet;
                ret.Data.Headers = [];
                ret.Data.Scripts = [];
                
                for(var x = 0, len = rs.fields.count; x < len; x++){
                    ret.Data.Headers.push(rs.fields(x).name);
                };
				
				while(!rs.EOF){
					var script = {
						ScriptID:	rs.fields("ScriptID").value,
						Category:	Helpers.DecodeHTML(rs.fields("Category").value),
						Title:	    Helpers.DecodeHTML(rs.fields("Title").value),
						Created:	new String(rs.fields("Created").value),
						CreatedBy:  rs.fields("CreatedBy").value,
					    Modified:   new String(rs.fields("Modified").value),
						ModifiedBy: rs.fields("ModifiedBy").value
					}

				    ret.Data.Scripts.push(script);
				
				    rs.MoveNext();
				}
			}
			
			return JSON.stringify(ret);					    
		},
	    
	    /*----------------------------------------------------------------------*/
	    SearchForTitles: function(){
			var ret =           {};
			ret.Success =       "";
			ret.Data =          0;
			ret.ErrorMessage =  "";
			
			var title = 	new String(Request.Form("title"));
			
			if(Helpers.IsNullOrEmpty(title)){
				ret.Success = 		false;
				ret.ErrorMessage = 	"No Title sent.";
				
				return JSON.stringify(ret);
			}
			
			
			queryName =          	"qryGetTitleByExactMatch";
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@Title", DB.DataTypes.String, title);
//ret.Debug = 		db;
//return JSON.stringify(ret);	

			db.Execute();
		
			ret.Success =       db.Success;
			ret.ErrorMessage =  db.ErrorMessage;
			ret.Debug = 		db;

			if(db.Success){
				ret.Data = db.RecordSet.recordCount;

			}
			
			return JSON.stringify(ret);		        
	    },
	    
	    /*----------------------------------------------------------------------*/
	    ExportScript: function(){
			var ret =           {};
			ret.Success =       false;
			ret.Data =          {};
			ret.ErrorMessage =  "";
			
			
			var scriptID = 		new String(Request.Form("ScriptID"));
			
			if(Helpers.IsNullOrEmpty(scriptID)){
				ret.ErrorMessage = 	"No ScriptID sent.";
				
				return JSON.stringify(ret);
			}
			
			var script =			{};
			script.scriptBlocks =	[];
			script.decisions =		[];
			
			
			var db, rs;
			
			/* GET SCRIPT FROM DB */
			db = new DB.DataCall();
			db.QueryName = 			"qryGetScript";
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
			
			db.Execute();
			
			
			
			/* RETURN ERROR IF NO MATCHING SCRIPT FOUND */
			if(db.RecordCount == 0){
				ret.ErrorMessage = "No Matching Script Found.";
				
				return JSON.stringify(ret);
			}
			
			if(db.Success == false){
				ret.ErrorMessage = db.ErrorMessage + " (qryGetScript)";
				
				return JSON.Stringify(ret);	
			}
			
			/* ADD SCRIPT INFO TO SCRIPT OBJECT */
			rs = db.RecordSet;
			script.ScriptID =	rs.fields("ScriptID").value;
			script.Category =	Server.HTMLEncode(rs.fields("Category").value).replace("'", "&#39");
			script.Title =		 Server.HTMLEncode(rs.fields("Title").value).replace("'", "&#39");
			script.Created =	Helpers.ToDateTimeString(rs.fields("Created").value, "MM/dd/yyyy hh:mm:ss");
			script.CreatedBy =  rs.fields("CreatedBy").value;
		    script.Modified =   Helpers.ToDateTimeString(rs.fields("Modified").value, "MM/dd/yyyy hh:mm:ss");
			script.ModifiedBy = rs.fields("ModifiedBy").value;

			
			/* GET SCRIPTBLOCKS FROM DB */
			db = new DB.DataCall();
			db.QueryName = 			"qryGetScriptBlocksByScriptID";
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
			
			db.Execute();
			
			if(db.Success == false){
				ret.ErrorMessage =	db.ErrorMessage + " (qryGetScriptBlocksByScriptID)";
				
				return JSON.Stringify(ret);	
			}
						
			/* ITERATE SCRIPTBLOCKS AND ADD TO SCRIPTBLOCK ARRAY IN SCRIPT OBJECT */
			rs = db.RecordSet;
			
			while(!rs.EOF){
				var scriptBlock ={
					ScriptBlockID:	rs.fields("ScriptBlockID").value,
					ScriptID:		rs.fields("ScriptID").value,
					DecisionID:		rs.fields("DecisionID").value,
					ScriptText:		Server.HTMLEncode(rs.fields("ScriptText").value).replace("'", "&#39"),
					Created:		Helpers.ToDateTimeString(rs.fields("Created").value, "MM/dd/yyyy hh:mm:ss"),
					CreatedBy:		rs.fields("CreatedBy").value,
					Modified:		Helpers.ToDateTimeString(rs.fields("Modified").value, "MM/dd/yyyy hh:mm:ss"),
					ModifiedBy:		rs.fields("ModifiedBy").value
				}
				
				script.scriptBlocks.push(scriptBlock);
				
				rs.MoveNext();
			}
			
			
			/* GET DECISIONS FROM DB */
			db = new DB.DataCall();
			db.QueryName = 			"qryGetDecisionsByScriptID";
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
			
			db.Execute();			
			
			if(db.Success == false){
				ret.ErrorMessage =	db.ErrorMessage + " (qryGetDecisionsByScriptID)";
				
				return JSON.Stringify(ret);	
			}
			
			/* ITERATE DECISIONS AND ADD TO DECISIONS ARRAY IN SCRIPT OBJECT */
			rs = db.RecordSet;
			
			while(!rs.EOF){
				
				var decision ={
					DecisionID:		rs.fields("DecisionID").value,
					ScriptID:		rs.fields("ScriptID").value,
					ScriptBlockID:	rs.fields("ScriptBlockID").value,
					DecisionTitle:	Server.HTMLEncode(rs.fields("DecisionTitle").value).replace("'", "&#39"),
					Order:			rs.fields("Order").value,
					Created:		Helpers.ToDateTimeString(rs.fields("Created").value, "MM/dd/yyyy hh:mm:ss"),
					CreatedBy:		rs.fields("CreatedBy").value,
					Modified:		Helpers.ToDateTimeString(rs.fields("Modified").value, "MM/dd/yyyy hh:mm:ss"),
					ModifiedBy:		rs.fields("ModifiedBy").value

				}
				
				script.decisions.push(decision);
				
				rs.MoveNext();
			}
			
			
			/* ADD SCRIPT TO RET OBJ SO THAT IT GETS RETURNED TO CLIENT-SIDE.
			 * CLIENT-SIDE WILL INJECT IT INTO A FORM AND SUBMIT THE FORM TO
			 * AdminScriptEditorExport.ASP WHICH WILL WRITE IT TO THE RESPONSE
			 * STREAM WITH CONTENTTYPE = APPLICATION/OCTET-STREAM SO THAT THE
			 * BROWSER OPENS A FILE SAVE DIALOG.
			 * WRAPPING Script IN QUOTES SO THAT CLIENT-SIDE DOESNT TRY TO 
			 * EVALUATE IT INTO AN OBJECT BECAUSE IT NEEDS TO BE LEFT AS A
			 * STRING */
			ret.Data.Script =	"\"" + JSON.stringify(script) + "\"";
			ret.Data.FileName = script.Title.replace(/\s+/gi, "_");
			ret.Success =		true;
			
			return JSON.stringify(ret);
			
			
	    },

	    /*----------------------------------------------------------------------*/
	    DeleteScript: function(){
			var ret =           {};
			ret.Success =       "";
			ret.Data =          0;
			ret.ErrorMessage =  "";
			
			var scriptID = 		new String(Request.Form("ScriptID"));
			
			if(Helpers.IsNullOrEmpty(scriptID)){
				ret.Success = 		false;
				ret.ErrorMessage = 	"No ScriptID sent.";
				
				return JSON.stringify(ret);
			}
			
			
			queryName =          	"qryDeleteScript";
			
			var db, rs;
			db = new DB.DataCall();
			db.QueryName = 			queryName;
			db.ConnectionString = 	DB.ConnectionStrings.Scripts;
			db.CommandType = 		DB.CommandTypes.StoredProc;
			
			db.AddParameter("@ScriptID", DB.DataTypes.String, scriptID);
//ret.Debug = 		db;
//return JSON.stringify(ret);	

			db.Execute();
		
			ret.Success =       db.Success;
			ret.ErrorMessage =  db.ErrorMessage;
			//ret.Debug = 		db;

			
			return JSON.stringify(ret);		        
	    }
		
}
/* END OF AJAX METHODS */

/*----------------------------------------------------------------------*/

var method = Request.QueryString("method") || "NoMethod";
var originalMethod = method;

if(!API[method]){
	method = "MethodNotFound";
}

Response.ContentType = "application/json";
Response.Write(API[method]());
%>
